package com.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.api.client.CartClient;
import com.mall.api.client.ProductClient;
import com.mall.api.dto.OrderDetailDTO;
import com.mall.api.vo.ProductVO;
import com.mall.common.exception.GlobalException;
import com.mall.common.utils.UserContext;
import com.mall.order.entity.dto.CreateOrderDTO;
import com.mall.order.entity.po.Order;
import com.mall.order.entity.po.OrderDetail;
import com.mall.order.mapper.OrderMapper;
import com.mall.order.service.OrderService;
import com.mall.order.service.OrderDetailService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderMapper orderMapper;

    private final ProductClient ProductClient;

    private final OrderDetailService orderDetailService;

    private final CartClient cartClient;

    @Override
    public String createOrder(CreateOrderDTO dto) {
        List<OrderDetailDTO> detailDTOS = dto.getDetails();
        // 1.2.获取商品id和数量的Map
        Map<Long, Integer> itemNumMap = detailDTOS.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Long> itemIds = itemNumMap.keySet();

        // 1. 远程调用商品服务，获取商品信息
        List<ProductVO> products = ProductClient.getProductsByIds(itemIds);
        if (products == null || products.isEmpty()) {
            throw new GlobalException("商品不存在");
        }

        // 2. 计算总金额
        BigDecimal totalAmount = products.stream()
                .map(ProductVO::getPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 3. 生成订单号（可用时间 + 用户ID + 随机数）
        String orderId = generateOrderId(UserContext.getUser());

        // 4. 构建订单主表
        Order order = new Order();
        order.setOrderNo(orderId);
        order.setUserId(UserContext.getUser());
        order.setTotalAmount(totalAmount);
        order.setStatus(0); // 0: 待支付
        order.setCreateTime(LocalDateTime.now());

        // 5. 保存订单
        orderMapper.insert(order);

        // 6. 构建订单详情列表并保存
        List<OrderDetail> details = products.stream().map(p -> {
            OrderDetail detail = new OrderDetail();
            detail.setOrderNo(orderId);
            detail.setProductId(p.getId());
            detail.setProductTitle(p.getTitle());
            detail.setPrice(p.getPrice());
            detail.setQuantity(1);
            return detail;
        }).toList();

        orderDetailService.saveBatch(details);

        //3.清理购物车商品
        cartClient.deleteCartItemByIds(itemIds);

        // 7. 减库存
        ProductClient.deductStock(detailDTOS);

        // 8. 返回订单号（前端可用于跳转支付页）
        return orderId;
    }

    @Override
    public boolean markAsPaid(Long orderNo) {
        // 构建更新条件：订单号匹配 + 状态为待支付（0）
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getStatus, 0) // 只有“待支付”的订单才能被支付
                .set(Order::getStatus, 1) // 已支付
                .set(Order::getPayTime, LocalDateTime.now());
        // 执行更新
        int updated = orderMapper.update(null, updateWrapper);

        return updated > 0;
    }

    /**
     * 生成唯一订单号：yyyyMMddHHmmss + userId + 4位随机数
     */
    private String generateOrderId(Long userId) {
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.format("%04d", new Random().nextInt(10000));
        return time + userId + random;
    }
}